package com.ctshk.rpc.order.airexpress.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ctshk.common.constant.ThirdUrlConstants;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.utils.HttpUtils;
import com.ctshk.rpc.order.airexpress.constants.AirportExpressConstants;
import com.ctshk.rpc.order.airexpress.dto.mtr.AirportExpressMTRDTO;
import com.ctshk.rpc.order.airexpress.dto.mtr.AirportExpressTicketMTRDTO;
import com.ctshk.rpc.order.airexpress.entity.AirportExpressOrder;
import com.ctshk.rpc.order.airexpress.enums.ProductCodeMTREnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 机场快线-港铁订单 服务实现类
 * </p>
 *
 * @author 胡广
 * @since 2021-02-23
 */
@Slf4j
@Component
public class AirportExpressOrderMTRService {
    @Value("${mtr.key}")
    private String MTR_KEY;
    @Value("${mtr.agent.id}")
    private String MTR_AGENT_ID;
    @Value("${mtr.agent.user}")
    private String MTR_AGENT_USER;
    @Value("${mtr.agent.pwd}")
    private String MTR_AGENT_PWD;
    @Value("${mtr.order.create}")
    private String MTR_CREATE_ORDER;

    private static final String ADULT = "0"; // 港铁旅客类型-成人
    private static final String CHILDREN = "3"; // 港铁旅客类型-小童
    /**
     * 构建港铁下单请求body并下单
     *
     * @param airportExpressOrder 称谓，姓，名，邮件，国籍
     * @return
     */
    public AirportExpressMTRDTO buildAndCreateMtrOrder(AirportExpressOrder airportExpressOrder) throws Exception {
        AirportExpressMTRDTO airportExpressMTRDTO = new AirportExpressMTRDTO();
        airportExpressMTRDTO.setAgentId(MTR_AGENT_ID);
        airportExpressMTRDTO.setAgentUser(MTR_AGENT_USER);
        airportExpressMTRDTO.setAgentPwd(MTR_AGENT_PWD);
        airportExpressMTRDTO.setType("QR"); // ["QR","Non-QR"]
        airportExpressMTRDTO.setTitle(airportExpressOrder.getGender() == 1 ? "Mr" : "Miss");
        airportExpressMTRDTO.setFirstName(airportExpressOrder.getSurname());
        airportExpressMTRDTO.setFamilyName(airportExpressOrder.getName());
        airportExpressMTRDTO.setCountry(airportExpressOrder.getContactCountryName());
        airportExpressMTRDTO.setEmail(airportExpressOrder.getContactEmail());
        airportExpressMTRDTO.setMerchantRef(airportExpressOrder.getOrderNumber());
        airportExpressMTRDTO.setTicket(new ArrayList<>());
        int adultQty = airportExpressOrder.getAdultTicketNumber();
        int childrenQty = airportExpressOrder.getChildrenTicketNumber();
        int totalQty = adultQty + childrenQty;
        // build checksum
        String checksum = DigestUtils.sha1Hex(MTR_AGENT_ID + "|" + airportExpressOrder.getContactEmail() + "|" + totalQty + "|" + MTR_KEY);
        log.info("【机场快线订单-港铁下单】create MTR order, checksum:{}", checksum);
        airportExpressMTRDTO.setChecksum(checksum);
        // 解析MTR产品编码
        buildTicket(airportExpressOrder.getAirportExpressId(), airportExpressMTRDTO.getTicket(), adultQty, childrenQty);
        String reqJson = JSON.toJSONString(airportExpressMTRDTO);
        log.info("【机场快线订单-港铁下单】create MTR order request:{}", reqJson);
        String markResultStr = null;
        try {
            markResultStr = HttpUtils.sendHttpSslPost(MTR_CREATE_ORDER, reqJson);
        } catch (Exception e) {
            log.error("【机场快线订单-港铁下单】create MTR order error, data:{}", e.getMessage(), e);
            throw e;
        }
        String markResultStrLog = markResultStr.length() > 1000 ? markResultStr.substring(0, 1000) : markResultStr;
        log.info("【机场快线订单-港铁下单】create MTR order response:{}", markResultStrLog);
        AirportExpressMTRDTO airportExpressMTRDTOResult = JSON.parseObject(markResultStr, AirportExpressMTRDTO.class);
        if (airportExpressMTRDTOResult.getErrorCode().equals("00") && CollectionUtils.isNotEmpty(airportExpressMTRDTOResult.getTicket())) {
            //创建订单成功
            return airportExpressMTRDTOResult;
        }
        return null;
    }

    /**
     * 构建机场快线港铁票列表
     *
     * @param airportExpressId
     * @param airportExpressTicketMTRList
     * @param adultQty
     * @param childrenQty
     */
    private void buildTicket(Long airportExpressId, List<AirportExpressTicketMTRDTO> airportExpressTicketMTRList,
                                    int adultQty, int childrenQty) {
        switch (String.valueOf(airportExpressId)) {
            case "1":
                //香港单程票
                airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(1, ProductCodeMTREnum.QSHA.getCode(), ADULT, adultQty));
                if (childrenQty >= 1) {
                    airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(2, ProductCodeMTREnum.QSHC.getCode(), CHILDREN, childrenQty));
                }
                break;
            case "2":
                //香港往返票
                airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(1, ProductCodeMTREnum.QRHA.getCode(), ADULT, adultQty));
                break;
            case "3":
                //九龙单程票
                airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(1, ProductCodeMTREnum.QSKA.getCode(), ADULT, adultQty));
                if (childrenQty >= 1) {
                    airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(2, ProductCodeMTREnum.QSKC.getCode(), CHILDREN, childrenQty));
                }
                break;
            case "4":
                //九龙往返票
                airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(1, ProductCodeMTREnum.QRKA.getCode(), ADULT, adultQty));
                break;
            case "5":
                //青山单程票
                airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(1, ProductCodeMTREnum.QSTA.getCode(), ADULT, adultQty));
                if (childrenQty >= 1) {
                    airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(2, ProductCodeMTREnum.QSTC.getCode(), CHILDREN, childrenQty));
                }
                break;
            case "6":
                //青山往返票
                airportExpressTicketMTRList.add(new AirportExpressTicketMTRDTO(1, ProductCodeMTREnum.QRTA.getCode(), ADULT, adultQty));
                break;
            default:
                throw new BusinessException(SystemError.AIREXPRESS_ORDER_60016); // 产品不存在
        }
    }
}
